<?php

namespace app\command;

use app\common\model\GoodsModel;
use app\common\model\OrderModel;
use app\common\model\OrderReceiptModel;
use app\common\model\StorageManageModel;
use app\common\model\StorageModel;
use GuzzleHttp\Client;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

class GetExpress extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('getexpress');
        // 设置参数

    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $this->exec();
    }

    public function exec()
    {
        $list = OrderReceiptModel::where('taskid', '>', 0)->whereNull('delivery_no')->select();
        if (!$list->toArray()) {
            $this->output->writeln('没有可获取的包裹单号');
        }
        foreach ($list as $item) {
            $order = OrderModel::find($item['order_id']);
            $manage = StorageManageModel::find($order['mid']);
            $client = new Client();
            try {
                $resp = $client->request('post', 'https://www.lipindao.com/api/goods/get_express', [
                    'headers'     => ['token' => $manage['token']],
                    'form_params' => [
                        'taskid' => $item['taskid'],
                    ]
                ]);

                $contents = ($resp->getBody()->getContents());
            } catch (\Exception $e) {
                $this->output->writeln($item['taskid'] . '请求结果：' . $e->getMessage());
                continue;
            }

            $data = json_decode($contents, true);
            if ($data['code'] == 1 && !empty($data['data']['express_no'])) {
                $item->save(['delivery_no' => $data['data']['express_no'], 'delivery_time' => time(), 'order_status' => 1]);
                $this->output->writeln($item['taskid'] . '获取成功' . $data['data']['express_no']);
            } else {
                $item->save(['taskmsg1' => $data['msg']]);
                $this->output->writeln($item['taskid'] . '获取失败:' . $data['msg']);
            }
        }


    }
}
